#!/usr/bin/env node

const { spawn } = require('child_process');
const path = require('path');

/**
 * 快速测试状态检查脚本
 */
class TestStatusChecker {
  constructor() {
    this.projectRoot = path.resolve(__dirname, '..');
  }

  /**
   * 运行命令并返回结果
   */
  async runCommand(command, args = [], timeout = 30000) {
    return new Promise((resolve, reject) => {
      const child = spawn(command, args, {
        cwd: this.projectRoot,
        stdio: 'pipe',
        shell: true,
      });

      let stdout = '';
      let stderr = '';

      child.stdout.on('data', (data) => {
        stdout += data.toString();
      });

      child.stderr.on('data', (data) => {
        stderr += data.toString();
      });

      const timer = setTimeout(() => {
        child.kill('SIGTERM');
        reject(new Error(`Command timed out after ${timeout}ms`));
      }, timeout);

      child.on('close', (code) => {
        clearTimeout(timer);
        resolve({
          code,
          stdout,
          stderr,
          success: code === 0,
        });
      });

      child.on('error', (error) => {
        clearTimeout(timer);
        reject(error);
      });
    });
  }

  /**
   * 检查单元测试
   */
  async checkUnitTests() {
    console.log('\n🧪 检查单元测试...');
    console.log('================================');
    
    try {
      const result = await this.runCommand('npm', ['run', 'test:unit'], 15000);
      
      if (result.success) {
        console.log('✅ 单元测试通过');
        
        // 提取测试统计信息
        const testMatch = result.stdout.match(/Tests:\s+(.+)/);
        const suiteMatch = result.stdout.match(/Test Suites:\s+(.+)/);
        const timeMatch = result.stdout.match(/Time:\s+(.+)/);
        
        if (testMatch) console.log(`📊 测试结果: ${testMatch[1]}`);
        if (suiteMatch) console.log(`📁 测试套件: ${suiteMatch[1]}`);
        if (timeMatch) console.log(`⏱️  执行时间: ${timeMatch[1]}`);
        
        return true;
      } else {
        console.log('❌ 单元测试失败');
        console.log('错误输出:', result.stderr);
        return false;
      }
    } catch (error) {
      console.log('❌ 单元测试执行失败:', error.message);
      return false;
    }
  }

  /**
   * 检查Mock系统
   */
  async checkMockSystem() {
    console.log('\n🎭 检查Mock系统...');
    console.log('================================');

    try {
      const result = await this.runCommand('node', ['-e', `
        const { createMockClient } = require('./tests/__mocks__/rabbitmq-mock');
        try {
          const client = createMockClient();
          console.log('Mock client methods:', Object.keys(client).join(', '));
          console.log('MOCK_AVAILABLE');
          process.exit(0);
        } catch (error) {
          console.log('MOCK_ERROR:', error.message);
          process.exit(1);
        }
      `], 5000);

      if (result.success && result.stdout.includes('MOCK_AVAILABLE')) {
        console.log('✅ Mock系统正常工作');
        return true;
      } else {
        console.log('❌ Mock系统失败');
        console.log('错误:', result.stderr);
        return false;
      }
    } catch (error) {
      console.log('❌ Mock系统检查失败:', error.message);
      return false;
    }
  }

  /**
   * 检查RabbitMQ连接 (可选)
   */
  async checkRabbitMQConnection() {
    console.log('\n🐰 检查RabbitMQ连接 (可选)...');
    console.log('================================');

    try {
      const result = await this.runCommand('node', ['-e', `
        process.env.USE_REAL_RABBITMQ = 'true';
        const { isRabbitMQAvailable } = require('./tests/test-config');
        isRabbitMQAvailable().then(available => {
          console.log(available ? 'AVAILABLE' : 'NOT_AVAILABLE');
          process.exit(available ? 0 : 1);
        }).catch(() => {
          console.log('NOT_AVAILABLE');
          process.exit(1);
        });
      `], 5000);

      if (result.success && result.stdout.includes('AVAILABLE')) {
        console.log('✅ RabbitMQ 连接可用 (可用于真实集成测试)');
        return true;
      } else {
        console.log('ℹ️  RabbitMQ 连接不可用 (使用Mock进行测试)');
        return false;
      }
    } catch (error) {
      console.log('ℹ️  RabbitMQ 连接检查超时 (使用Mock进行测试)');
      return false;
    }
  }

  /**
   * 检查简单集成测试
   */
  async checkSimpleIntegration() {
    console.log('\n🔗 检查简单集成测试...');
    console.log('================================');
    
    try {
      const result = await this.runCommand('npm', ['run', 'test:integration'], 20000);
      
      if (result.success) {
        console.log('✅ 简单集成测试通过');
        return true;
      } else {
        console.log('❌ 简单集成测试失败');
        console.log('错误输出:', result.stderr.substring(0, 500));
        return false;
      }
    } catch (error) {
      console.log('❌ 简单集成测试超时或失败:', error.message);
      return false;
    }
  }

  /**
   * 检查代码质量
   */
  async checkCodeQuality() {
    console.log('\n📝 检查代码质量...');
    console.log('================================');
    
    try {
      // 检查TypeScript编译
      const tscResult = await this.runCommand('npx', ['tsc', '--noEmit'], 10000);
      
      if (tscResult.success) {
        console.log('✅ TypeScript 编译通过');
      } else {
        console.log('❌ TypeScript 编译失败');
        console.log('错误:', tscResult.stderr.substring(0, 300));
        return false;
      }
      
      return true;
    } catch (error) {
      console.log('❌ 代码质量检查失败:', error.message);
      return false;
    }
  }

  /**
   * 生成测试报告
   */
  generateReport(results) {
    console.log('\n📋 测试状态报告');
    console.log('================================');
    
    const totalChecks = Object.keys(results).length;
    const passedChecks = Object.values(results).filter(Boolean).length;
    const successRate = Math.round((passedChecks / totalChecks) * 100);
    
    console.log(`📊 总体状态: ${passedChecks}/${totalChecks} 通过 (${successRate}%)`);
    console.log('');
    
    Object.entries(results).forEach(([check, passed]) => {
      const icon = passed ? '✅' : '❌';
      const status = passed ? '通过' : '失败';
      console.log(`${icon} ${check}: ${status}`);
    });
    
    console.log('');
    
    if (successRate >= 80) {
      console.log('🎉 测试状态良好！');
    } else if (successRate >= 60) {
      console.log('⚠️  测试状态一般，需要改进');
    } else {
      console.log('🚨 测试状态较差，需要立即修复');
    }
    
    return successRate;
  }

  /**
   * 主执行函数
   */
  async run() {
    console.log('🧪 RabbitMQ 测试状态检查器');
    console.log('============================');
    
    const results = {};
    
    // 执行各项检查
    results['单元测试'] = await this.checkUnitTests();
    results['代码质量'] = await this.checkCodeQuality();
    results['Mock系统'] = await this.checkMockSystem();

    // 检查RabbitMQ连接 (可选)
    const rabbitMQAvailable = await this.checkRabbitMQConnection();

    // 运行Mock集成测试 (总是可以运行)
    results['Mock集成测试'] = await this.checkSimpleIntegration();

    // 只有在RabbitMQ可用时才标记为额外功能
    if (rabbitMQAvailable) {
      console.log('\n✨ 额外功能: 真实RabbitMQ集成测试可用');
    }
    
    // 生成报告
    const successRate = this.generateReport(results);
    
    // 返回适当的退出码
    process.exit(successRate >= 80 ? 0 : 1);
  }
}

// 运行检查器
if (require.main === module) {
  const checker = new TestStatusChecker();
  checker.run().catch(error => {
    console.error('💥 检查器执行失败:', error);
    process.exit(1);
  });
}

module.exports = TestStatusChecker;
